package org.blogspot.t0yv0.marcalog.util

import java.io._
import org.marc4j._
import org.marc4j.marc._

object Marc {

  private def parseSubfield(field: DataField, sub: Char) = {
    field match {
      case null => "";
      case _    =>
        field.getSubfield(sub) match {
          case null      => "";
          case subfield  =>
            subfield.getData() match {
              case null  => "";
              case data  => data;
            }
        }
    }
  }

  private def parseField(record: Record, field: String, sub: Char) = {
    record.getVariableField(field) match {
      case f: DataField => parseSubfield(f, sub);
      case _            => "";
    }
  }

  private def parsePerson(record: Record) =
    parseField(record, "100", 'a')

  private def parseTitle(record: Record) = {
    var f = parseField(record, "245", 'a');
    if (f.endsWith(":") || f.endsWith("/"))
      f.substring(0, f.length - 1).trim();
    else
      f.trim()
  }

  private def parseISBN(record: Record) =
    parseField(record, "020", 'a')

  def parse(record: Record) =
    (parseTitle(record),
     parsePerson(record),
     parseISBN(record))

}
